package com.inspur.sc.springboot.controller;

import com.inspur.sc.springboot.convert.SysGroupConvertSysGroupVO;
import com.inspur.sc.springboot.entity.SysGroup;
import com.inspur.sc.springboot.entity.SysRole;
import com.inspur.sc.springboot.service.SysGroupRoleService;
import com.inspur.sc.springboot.service.SysGroupService;
import com.inspur.sc.springboot.utils.ResponseUtil;
import com.inspur.sc.springboot.vo.DataTablesVO;
import com.inspur.sc.springboot.vo.QueryVO;
import com.inspur.sc.springboot.vo.ResponseVO;
import com.inspur.sc.springboot.vo.SysGroupVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("api/group")
public class SysGroupController {

    @Autowired
    private SysGroupService groupService;

    @Autowired
    private SysGroupRoleService groupRoleService;

    @PostMapping("findAll")
    public DataTablesVO<SysGroup> findAll(QueryVO queryVO){
        Integer pageNo=queryVO.getStart()/queryVO.getLength();
        Pageable pageable= PageRequest.of(pageNo,queryVO.getLength());
        Page<SysGroup> page= groupService.findAll(pageable);
        DataTablesVO<SysGroup> result=new DataTablesVO<>(page.getContent(),page.getTotalElements(),page.getTotalElements(),queryVO.getDraw());
        return result;
    }

    @PostMapping("save")
    public ResponseEntity<ResponseVO> save(@RequestBody SysGroupVO groupVO){
        SysGroup group= SysGroupConvertSysGroupVO.convert(groupVO);
        List<Integer> roleIds=groupVO.getRoles().toJavaList(Integer.class);
        boolean isSave=groupService.save(group,roleIds);
        if(isSave){
            return ResponseUtil.success("保存成功！",true);
        }
        return ResponseUtil.success("保存失败！",false);
    }

    @GetMapping("getGroup")
    public ResponseEntity<ResponseVO> getGroup(@RequestParam("id") Integer id){
        SysGroupVO groupVO=groupService.findById(id);
        List<SysRole> roles= groupRoleService.findRoleByGroupId(id);
        groupVO.setRoles(roles);
        return ResponseUtil.success(groupVO);
    }

    @GetMapping("delete")
    public ResponseEntity<ResponseVO> delete(@RequestParam("id") Integer id){
        boolean isDel=groupService.deleteById(id);
        if(isDel){
            return ResponseUtil.success("删除成功！",true);
        }
        return ResponseUtil.success("删除失败！",false);
    }
}
